package com.wswy.wzcx.ui.wzdb

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.format.Formatter
import android.text.style.ForegroundColorSpan
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.utils.IntentUtils
import com.che.libcommon.utils.ToastUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import com.wswy.wzcx.R
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.getColor
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.statistics.BizReport
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.utils.RxUtils
import com.wzcx.util.ImageUtil
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.fragment_user_face.*
import timber.log.Timber
import java.io.File


class UserFaceFragment : CBaseFragment() {

    companion object {
        const val TAG = "UserFaceFragment"
        private const val REQ_PICK_GALLERY = 310
    }


    override fun getContentLayoutId(): Int {
        return R.layout.fragment_user_face
    }

    override fun getFragmentTitle(): String {
        return "补充资料"
    }


    private var hasPerm = false
    private var showCamera = true //显示相机预览
    private var cameraStarted = false

    @SuppressLint("CheckResult")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        tv_user_hint.text = SpannableStringBuilder().apply {
            append("应交管要求，粤牌违章办理需上传")
            append(SpannableString("上传车主照片").apply {
                setSpan(ForegroundColorSpan(getColor(R.color.textColorPrimary)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })
        }

        RxPermissions(this).request(Manifest.permission.CAMERA).subscribe {
            if (it) {
                hasPerm = true
                startCamera()
            } else {
                ToastUtils.showText("没有相机权限")
            }
        }

        btn_take.onClick {
            if (hasPerm) {
                camera_view?.setOnPictureBytesAvailableListener { bytes, rotationDegrees ->
                    val r = ImageUtil.getOrientation(bytes)
                    Timber.e("----r:$r")
                    val ret = kotlin.runCatching {
                        takeImage(ImageUtils.bytes2Bitmap(bytes), rotationDegrees)
                    }
                    if (ret.isFailure) {
                        BizReport.postCatchedException(ret.exceptionOrNull())
                        ToastUtils.showText("拍照失败，请使用手机相机拍照")
                    }
                }
                camera_view?.takePicture()
            }
        }

        btn_choose_photo.onClick {
            startGallery()
        }
    }


    private fun startCamera() {
        if (cameraStarted) {
            return
        }
        camera_view?.setOnCameraErrorListener {
            Timber.e(it)
        }
        camera_view?.start()
        cameraStarted = true
    }

    private fun startGallery() {
        if (hasPerm) {
            startActivityForResult(IntentUtils.getPickGallery(), REQ_PICK_GALLERY)
        }
    }


    private fun printBitmap(bitmap: Bitmap?, msg: String? = null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Timber.e("${msg}   ${bitmap?.width}    ${bitmap?.height}  ${Formatter.formatFileSize(requireContext(), bitmap?.allocationByteCount?.toLong()
                    ?: 0L)}")
        }
    }

    @SuppressLint("CheckResult")
    private fun takeImage(bitmap: Bitmap, rotationDegrees: Int) {
        // 拍照完成 显示截取后的图片

        Flowable.fromCallable {
            printBitmap(bitmap)
            val r = (360 - (camera_view?.defaultOrientation ?: 0 + rotationDegrees) % 360) % 360
            Timber.e("----$rotationDegrees     ${camera_view?.defaultOrientation}   $r")
            val matrix = Matrix()
            matrix.preRotate(r.toFloat())
            matrix.postScale(-1f, 1f)
            val bm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true)

            bitmap.recycle()

            val lm = (ll_main_content.width - camera_view.width) / 2

            val maskRect = Rect(lm, 0, (camera_view?.width ?: 0) + lm, camera_view?.height ?: 0
            + SizeUtils.dp2px(80f))
            val saveBm = Bitmap.createBitmap(bm, maskRect.left, maskRect.top, maskRect.width(), maskRect.height(), null, true)
            printBitmap(saveBm)

            val path = arguments?.getString(Constants.EXTRA_DATA)
            ImageUtils.save(saveBm, File(path), Bitmap.CompressFormat.JPEG, true)
            path
        }.compose(RxUtils.io2main()).subscribe {
            camera_view?.stop()
            cameraStarted = false
            activity?.setResult(Activity.RESULT_OK, Intent().apply {
                putExtra(Constants.EXTRA_DATA, it)
            })
            finish()
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQ_PICK_GALLERY) {
            if (data != null) {
                camera_view?.stop()
                cameraStarted = false
                val path = arguments?.getString(Constants.EXTRA_DATA)
                val abPath = ImageUtils.getBitmap(File(IntentUtils.extraImageFromGallery(requireContext(), data)).absolutePath)
                ImageUtils.save(abPath, File(path), Bitmap.CompressFormat.JPEG, true)
                activity?.setResult(Activity.RESULT_OK, Intent())
                finish()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (hasPerm && showCamera) {
            startCamera()
        }
    }

    override fun onPause() {
        super.onPause()
        if (hasPerm) {
            camera_view?.stop()
        }
        showCamera = false
        cameraStarted = false
    }

    override fun onDestroy() {
        super.onDestroy()
        if (hasPerm) {
            camera_view?.stop()
        }
        cameraStarted = false
    }

}